package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetmealController {
    @Autowired
    CategoryService categoryService;

    @Autowired
    SetmealDishService setmealDishService;
    @Autowired
    SetmealService setmealService;

    //新增套餐

    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)//清除setmealCache名称下,所有的缓存数据
    @ApiOperation(value = "新增套餐接口")
    public R<String> save(@RequestBody SetmealDto setmealDto) {

        //新增套参分类
        setmealService.save(setmealDto);
        //新增菜品
        Long id = setmealDto.getId();
        //获取相关菜品的集合
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            //设置setmealDish中的setmealid
            setmealDish.setSetmealId(id);
        }
        setmealDishService.saveBatch(setmealDishes);
        return R.success("添加成功！！");
    }



    //分页查询+模糊查询
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams(
            {
               @ApiImplicitParam(name = "page",value = "页码",required = true),
               @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
               @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
            }
    )
    public R<Page> page(Integer page, Integer pageSize, String name) {

        Page<Setmeal> setmealPage = new Page<>(page, pageSize);

        Page<SetmealDto> setmealDtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);

        setmealService.page(setmealPage, wrapper);


        List<Setmeal> records = setmealPage.getRecords();

        ArrayList<SetmealDto> setmealDtos = new ArrayList<>();

        for (Setmeal record : records) {
            //通过获取setmeal中的categoryid来获取category中id
            //从而获取category对象 来获取catgoryName
            SetmealDto setmealDto = new SetmealDto();

            Long id = record.getCategoryId();

            Category category = categoryService.getById(id);

            String categoryName = category.getName();

            setmealDto.setCategoryName(categoryName);

            BeanUtils.copyProperties(record, setmealDto);

            setmealDtos.add(setmealDto);
        }
        setmealDtoPage.setTotal(setmealPage.getTotal());

        setmealDtoPage.setRecords(setmealDtos);

        return R.success(setmealDtoPage);
    }

    //删除操作

   @DeleteMapping
   @Transactional
   @CacheEvict(value = "setmealCache",allEntries = true) //清除setmealCache名称下,所有的缓存数据
   @ApiOperation(value = "套餐删除接口")
    public R<String> delete(@RequestParam List<Long> ids){
        //先删除套餐
       LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
//       wrapper.in(Setmeal::getId,ids);
       //找出寻找起售状态的情况
       wrapper.eq(Setmeal::getStatus,1);
       int count = setmealService.count(wrapper);
       if(count>0){
           //如果不能删除，抛出一个业务异常
           throw new CustomException("套餐正在售卖中，不能删除");
       }
       setmealService.removeByIds(ids);
       //再删除套餐菜品
       LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
       for (Long id : ids) {
           wrapper1.eq(SetmealDish::getSetmealId,id);
           setmealDishService.remove(wrapper1);
       }
       return R.success("删除套餐成功！！");
}
   //起售/停售套餐
   @PostMapping("/status/{status}")
   public R<String> status(Setmeal setmeal,@RequestParam List<Long> ids){
       //获取修改setmeal对象的集合
       List<Setmeal> setmeals = setmealService.listByIds(ids);

       for (Setmeal setmeal1 : setmeals) {
           //设置每一个状态的属性
           setmeal1.setStatus(setmeal.getStatus());
       }
       //更新集合的操作
       setmealService.updateBatchById(setmeals);
       return R.success("修改套餐售卖状态成功！！！");
   }

   //修改数据的回显
    @GetMapping("/{id}")
    public R<SetmealDto> updateById(@PathVariable  Long id){
        //回显套餐
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        //把setmeal数据拷贝给setmealdto数据
        BeanUtils.copyProperties(setmeal,setmealDto);
        //首先回显出setmeal，将setmeal数据拷贝给setmealdto中 然后回显出dish菜品
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        //查找出SetmealDish中setmealid与setmeal的id相等的情况
        wrapper.eq(SetmealDish::getSetmealId,setmeal.getId());
        List<SetmealDish> list = setmealDishService.list(wrapper);
        //将菜品数据显示到setmealdto中
        setmealDto.setSetmealDishes(list);
        return R.success(setmealDto);
    }

    //修改数据
    @PutMapping
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto){
        //首先正常修改sermeal套餐
       setmealService.updateById(setmealDto);
       //获取setmeal中的id
        Long setmealDtoId = setmealDto.getId();
        //修改setmealdish的套餐要先删除后添加（setmeal不用逻辑删除即可）
        //删除setmealdish的套餐
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,setmealDtoId);
        setmealDishService.remove(wrapper);
        //添加setmealdish的套餐
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDtoId);
            setmealDishService.save(setmealDish);
        }
//        setmealDishService.saveBatch(setmealDishes);
        return R.success("修改成功");
    }

//    根据套餐分类id查询该套餐分类下的套餐
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status" ,unless = "#result.data.size()==0")
    @ApiOperation(value = "套餐条件查询接口")
     public R<List<Setmeal>> list(Setmeal setmeal){
       //查询套餐中状态为1的情况
       //查询setmeal套餐中categoryid与category中id相等的情况
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        wrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        List<Setmeal> list = setmealService.list(wrapper);
        return R.success(list);

    }
//    根据套餐分类id查询该套餐分类下的套餐
//     @GetMapping("/list")
//     @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
//     public R<List<SetmealDto>> list(Setmeal setmeal){
//       //查询套餐中状态为1的情况
//       //查询setmeal套餐中categoryid与category中id相等的情况
//        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(setmeal.getStatus()!=null,Setmeal::getStatus,1);
//        wrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
//        List<Setmeal> setmeallist = setmealService.list(wrapper);
//        ArrayList<SetmealDto> setmealDtos = new ArrayList<>();
//         for (Setmeal setmeal1 : setmeallist) {
//             SetmealDto setmealDto = new SetmealDto();
//             //将setmeal数据拷贝到setmealdto数据中
//             BeanUtils.copyProperties(setmeal1,setmealDto);
//             //将每一种STEMAL对应dish在setmealdish中dishid找出
//             LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
//             //找出每一个套餐与套餐菜品对应的id数据
//             wrapper1.eq(SetmealDish::getSetmealId,setmeal1.getId());
//             List<SetmealDish> setmealDishList = setmealDishService.list(wrapper1);
//             //将套餐菜品放到stemaldto中
//             setmealDto.setSetmealDishes(setmealDishList);
//             setmealDtos.add(setmealDto);
//         }
//         return R.success(setmealDtos);
//
//    }
   //获取套餐中图片
    @GetMapping("/dish/{id}")
    public R<List<SetmealDto>> list1(Setmeal setmeal) {
        //查询套餐中状态为1的情况
        //查询setmeal套餐中categoryid与category中id相等的情况
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, 1);
        wrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        List<Setmeal> setmeallist = setmealService.list(wrapper);
        ArrayList<SetmealDto> setmealDtos = new ArrayList<>();
        for (Setmeal setmeal1 : setmeallist) {
            SetmealDto setmealDto = new SetmealDto();
            //将setmeal数据拷贝到setmealdto数据中
            BeanUtils.copyProperties(setmeal1, setmealDto);
            //将每一种STEMAL对应dish在setmealdish中dishid找出
            LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
            //找出每一个套餐与套餐菜品对应的id数据
            wrapper1.eq(SetmealDish::getSetmealId, setmeal1.getId());
            List<SetmealDish> setmealDishList = setmealDishService.list(wrapper1);
            //将套餐菜品放到stemaldto中
            setmealDto.setSetmealDishes(setmealDishList);
            setmealDtos.add(setmealDto);
        }
        return R.success(setmealDtos);
    }

}
